package com.zhang.third.day06;

import com.zhang.third.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;

/**
 * @title: 实时热门商品--简化版
 * @author: zhang
 * @date: 2022/4/9 09:46
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("/Users/apple/IdeaProjects/flink_1.13/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0], arr[1], arr[2], arr[3],
                                Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                )
                .windowAll(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
                .process(new TopN(3))
                .print();

        env.execute();
    }

    public static class TopN extends ProcessAllWindowFunction<UserBehavior, String, TimeWindow> {
        private int n;

        public TopN(int n) {
            this.n = n;
        }

        @Override
        public void process(ProcessAllWindowFunction<UserBehavior, String, TimeWindow>.Context context, Iterable<UserBehavior> elements, Collector<String> out) throws Exception {
            HashMap<String, Long> hashMap = new HashMap<>();
            for (UserBehavior e : elements) {
                if (!hashMap.containsKey(e.productId)) {
                    hashMap.put(e.productId, 1L);
                } else {
                    hashMap.put(e.productId, hashMap.get(e.productId) + 1L);
                }
            }
            ArrayList<Tuple2<String, Long>> arrayList = new ArrayList<>();
            for (String key : hashMap.keySet()) {
                arrayList.add(Tuple2.of(key, hashMap.get(key)));
            }

            arrayList.sort(new Comparator<Tuple2<String, Long>>() {
                @Override
                public int compare(Tuple2<String, Long> o1, Tuple2<String, Long> o2) {
                    return (int) (o2.f1 - o1.f1);
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("=====================================\n");
            result.append("窗口" + new Timestamp(context.window().getStart()) + "~" +
                    "" + new Timestamp(context.window().getEnd()) + "\n");
            for (int i = 0; i < n; i++) {
                Tuple2<String, Long> tmp = arrayList.get(i);
                result.append("NO." + (i + 1) + ".商品ID是：" + tmp.f0 + ",浏览次数是：" + tmp.f1 + "\n");
            }
            result.append("=====================================\n");

            out.collect(result.toString());

        }
    }
}
